<template>
  <!-- wave line -->
  <div>
    <div class="recpower">
      <div class="recpowerbox">
        <div class="recpowerx" />
        <!-- <div class="recpowert">0/0</div> -->
      </div>
      <audio class="recPlays" style="width: 100%" />
    </div>
    <div class="recwave" />
  </div>
</template>

<script>
import '@/libs/Recorder/recorder-core.js';
import '@/libs/Recorder/waveview.js';
import { isSafari } from '@/utils/common.js';

export default {
  name: 'RecorderWave',
  props: {
    recorderWaveVisible: {
      type: Boolean,
      required: true,
    },
  },
  data() {
    return {
      // 音波图实例
      recorderWave: null,
      aiVoice: null,
    };
  },
  computed: {},
  watch: {},
  mounted() {
    this.$nextTick(() => {
      this.aiVoice = document.querySelector('.recPlay');
      this.recorderWave = window.Recorder.WaveView({ elem: '.recwave' });
    });
  },
  methods: {
    receiveVoiceData(buffers, level, time, sampleRate) {
      // console.log(buffers, level, time, sampleRate);
      // document.querySelector('.recpowerx').style.width = level + '%';
      // document.querySelector('.recpowert').innerHTML = time + 'ms/' + level;
      this.recorderWave.input(buffers[buffers.length - 1], level, sampleRate);
    },
    playAiVoice(voicePath, callback) {
      if (voicePath) {
        const self = this;
        if (isSafari()) {
          callback && callback();
        } else {
          this.aiVoice.src = process.env.VUE_APP_BASE_API + '/' + voicePath;
          this.aiVoice.play();
          localStorage.setItem('isfinished', false);
          var event = () => {
            self.aiVoice.removeEventListener('ended', event, true);
            console.log('语音播放结束', self.aiVoice.src);
            URL.revokeObjectURL(self.aiVoice.src);
            localStorage.setItem('isfinished', true);
            callback && callback();
          };
          this.aiVoice.addEventListener('ended', event, true);
          this.aiVoice.addEventListener(
            'error',
            function (error) {
              self.aiVoice.removeEventListener('ended', event, true);
              URL.revokeObjectURL(self.aiVoice.src);
              console.error('语音文件加载失败', error, self.aiVoice.src);
              callback && callback();
            },
            true
          );
        }
      } else {
        callback && callback();
      }
    },
  },
};
</script>

<style>
.recpower {
  position: absolute;
}
.recpowerbox {
  height: 80px;
  width: 100%;
  /* background: #fff; */
  position: relative;
}
.recpowerx {
  height: 80px;
  /* background: #fff; */
  position: absolute;
  width: 15%;
}
.recpowert {
  /* color: #fff; */
  padding-left: 50px;
  line-height: 40px;
  position: relative;
}
.recwave {
  height: 80px;
  width: 600px;
  /* border: 1px solid #fff; */
  box-sizing: border-box;
  display: inline-block;
}
</style>
